#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>  // 系统错误码
#include "linklist.h"

linklist init_list(void) //初始化链表
{
    linklist head = malloc(sizeof(linknode));
    if(head == NULL){
        perror("初始化节点失败");
        return NULL;
    }
    head->next = NULL;
    return head;
}

linklist new_node(const student *someone) //生成新节点
{
    linklist new = malloc(sizeof(linknode));
    if(new == NULL){
        perror("新节点生成失败");
        return NULL;
    }
    new->data = *someone;
    new->next = NULL;
    return new;  //为什么没写return new 也能在后续插入节点
}

void add_list(linklist head, linklist new_node) //插入新节点
{
    //找到尾节点
    linklist tail = head;
    for(;tail->next != NULL; tail = tail->next);

    //链接节点
    tail->next = new_node;

}

void list_for_each(linklist head) //遍历节点并输出
{
    linklist current = head->next;
    while(current != NULL)
    {
        printf("姓名:%s\t年龄:%d\t\t分数:%.1f\n", 
            current->data.name, current->data.age, current->data.score);
        current = current->next;
    }
    printf("\n");
}

bool student_cmp(student stu1, student *stu2)
{
    if(strcmp(stu1.name, stu2->name) == 0 && stu1.age == stu2->age && stu1.score == stu2->score)
        return true;
    else
        return false;
}

void list_del(linklist head, student *someone) //删除指定节点
{
    if(head == NULL || head->next == NULL)
        return;
    //找到指定节点
    linklist p = head;
    while(1){
        if(student_cmp(p->next->data, someone)){//删除指定节点并链接断点处
            if(p->next->next == NULL){
                free(p->next);
                p->next = NULL;
                break;
            }
            linklist k = p->next->next;
            free(p->next);
            p->next = k;
            break;
        }
        p = p->next;
    }
    return;
}

void destory_list(linklist head) //删除列表
{
    linklist p, k;
    for(p = head->next; p != NULL; p = k){
        k = p->next;
        free(p);
    }
    p = NULL;
}